#include <QEventLoop>
#include "biblereaderdownloader.h"
#include "Logger.h"

BibleReaderDownloader::BibleReaderDownloader(QUrl &url, QObject *parent) :
    QObject(parent), url(url)
{
    data.clear();
    isFinished = false;
    errorString = "";
    errorCode = QNetworkReply::NoError;
    manager = new QNetworkAccessManager(this);
    // connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

}

BibleReaderDownloader::BibleReaderDownloader(QString &urlstr, QObject *parent):
    QObject (parent)
{
    url = QUrl(urlstr);
    data.clear();
    isFinished = false;
    manager = new QNetworkAccessManager(this);
}

BibleReaderDownloader::~BibleReaderDownloader()
{
    if (manager) {
        delete manager;
    }
}

QByteArray BibleReaderDownloader::getData() const
{
    return data;
}

QUrl BibleReaderDownloader::getUrl() const
{
    return url;
}

void BibleReaderDownloader::setUrl(const QUrl &value)
{
    url = value;
}

bool BibleReaderDownloader::getIsFinished() const
{
    return isFinished;
}

QNetworkReply::NetworkError BibleReaderDownloader::getErrorCode() const
{
    return errorCode;
}

void BibleReaderDownloader::setErrorCode(const QNetworkReply::NetworkError &value)
{
    errorCode = value;
}

void BibleReaderDownloader::start(int block)
{
    data.clear();
    if (block == BLOCK) {
        QEventLoop el;
        reply = manager->get(QNetworkRequest(url));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(proccessError(QNetworkReply::NetworkError)));
        connect(reply, &QNetworkReply::downloadProgress, this, &BibleReaderDownloader::processDownloadProgress);
        connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
        connect(manager, SIGNAL(finished(QNetworkReply*)), &el, SLOT(quit()));
        el.exec(QEventLoop::ExcludeUserInputEvents);
    } else {
        reply = manager->get(QNetworkRequest(url));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(proccessError(QNetworkReply::NetworkError)));
        connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64)));
        connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    }
}

void BibleReaderDownloader::replyFinished(QNetworkReply *reply)
{
    data = reply->readAll();
    isFinished = true;

    emit finished();
}

void BibleReaderDownloader::proccessError(QNetworkReply::NetworkError code)
{
    errorCode = code;
    emit finished();
}

void BibleReaderDownloader::processDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    LOG_INFO() << bytesReceived << ","<<bytesTotal;
    emit downloadProgress(bytesReceived, bytesTotal);
}



